package dbshelper

import (
	"errors"
	"fmt"
	"gitee.com/wanjimao/main-common-utils/helper"
	"strings"
)

/**
*  InsertHelper
*  @Description: Insert封装
 */
type InsertHelper struct {
}

/**
*  UpdateHelperObject
*  @Description: Update封装
 */
var InsertHelperObject InsertHelper

/**
 *  updateBatchByIds
 *  @Description:
 *  @receiver receiver
 *  @param paramsSet
 *  @param tableName
 *  @return string
 *  @return error
 */
func (h *InsertHelper) GetInsertSql(paramsSlice []map[string]interface{}, tableName string) ([]interface{}, error) {
	res := make([]interface{}, 0)
	getStr := func(data interface{}) string {
		return helper.InterfaceHelperObject.ToString(data)
	}
	if 0 == len(paramsSlice) {
		return res, errors.New(fmt.Sprintf("待插入的数据不允许为空;%s", getStr(paramsSlice)))
	}
	if "" == tableName {
		return res, errors.New(fmt.Sprintf("待插入的表名不允许为空;%s", getStr(paramsSlice)))
	}
	keySlice := make([]string, 0)
	for key, _ := range paramsSlice[0] {
		keySlice = append(keySlice, key)
	}
	if len(keySlice) < 1 {
		return res, errors.New(fmt.Sprintf("待插入的数据key不允许为空;%s", getStr(paramsSlice)))
	}
	//sqlBase := "INSERT INTO "+tableName+" (`project_id`,`url`,`type`) VALUES "
	sqlBase := "INSERT INTO " + tableName + " (`" + strings.Join(keySlice, "`,`") + "`) VALUES "
	params := make([]interface{}, 0)
	tmp1 := make([]string, 0)
	for _, i2 := range paramsSlice {
		tmpItem := make([]string, 0)
		for _, i4 := range keySlice {
			value, has := i2[i4]
			if !has {
				return res, errors.New(fmt.Sprintf("待插入的数据key无对应的值;%s", getStr(paramsSlice)))
			}
			tmpItem = append(tmpItem, "?")
			params = append(params, value)
		}
		tmpString := "(" + strings.Join(tmpItem, ",") + ")"
		tmp1 = append(tmp1, tmpString)
	}
	sqlBase += strings.Join(tmp1, ",")
	res = append(res, sqlBase)
	res = append(res, params...)
	return res, nil
}
